package evocarcassonne.tileseteditor.ui.swing.components;

import evocarcassonne.tileseteditor.managers.TileManager;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;


public class TilesTree extends JTree {

    public DefaultTreeModel treeModel;
    public DefaultMutableTreeNode rootNode;

    public TilesTree() {

        rootNode = new DefaultMutableTreeNode("Tuiles");

        treeModel = new DefaultTreeModel(rootNode);

        setModel(treeModel);

        setEditable(false);

        getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        setShowsRootHandles(true);
    }

    public DefaultMutableTreeNode addObject(int number) {

        DefaultMutableTreeNode childNode = new TileNode(number);
        treeModel.insertNodeInto(childNode, rootNode, rootNode.getChildCount());

        scrollPathToVisible(new TreePath(childNode.getPath()));
        return childNode;
    }


    public void removeSelectedObject() {
        DefaultMutableTreeNode node = null;
        TreePath parentPath = getSelectionPath();

        if (parentPath != null) {

            node = (DefaultMutableTreeNode) (parentPath.getLastPathComponent());

            if (node != rootNode) {


                TileManager.removeTile(((TileNode) node).getNumber());


                treeModel.removeNodeFromParent(node);


            }
        }
    }
}
